<?php

class Widgets extends Core {
    
    
    function __construct() {
        
        parent::__construct();
        
        if (!$this->usr->check_rights('admin')) {
            
            show_error('Нет доступа!!!');
        }
        
        $this->load->model('modmanager');
        $this->load->model('adminmodel');
        
        $this->load->language('admin');
        
        $this->load->helper('adminhelp');
        $this->load->helper('language');
    }
    
    
    public function index() {
        
        foreach($this->adminmodel->get_widget()->result_array() as $row) {
            
            $modul = $this->modmanager->get_modul($row['modul']);
            $data['widgets'][$row['container']][] = array_merge($row, array('modul_title' => $modul->title, 'widget_title' => $modul->widgets[$row['method']]['title']));
        }
        
        $this->set_bread_crumbs(lang('menu_widgets'), 'widgets');
        
        parent::render($data, 'widget/index');
    }
    
    
    public function add() {
        
        $this->load->helper('form');
        
        if ( $this->input->post('add', TRUE) ) {
            
            $this->load->library('form_validation');
            
            $this->form_validation->set_rules('container',  'lang:widget_field_container',   'trim|required|xss_clean');
            $this->form_validation->set_rules('title',      'lang:widget_field_title',       'trim|xss_clean');
            $this->form_validation->set_rules('modul',      'lang:widget_field_modul',       'trim|required|xss_clean');
            $this->form_validation->set_rules('method',     'lang:widget_field_method',      'trim|required|xss_clean');
            $this->form_validation->set_rules('order',      'lang:widget_field_order',       'trim|required|is_natural|xss_clean');
            $this->form_validation->set_rules('widget[]',   'lang:widget_field_parametrs',   '');
            $this->form_validation->set_rules('cache[]',    'lang:widget_field_parametrs',   '');
            
            //Правила для валидации параметров виджета
            $modul = $this->modmanager->get_modul($this->input->post('modul'));
            $widget = $modul->widgets[$this->input->post('method')];
            
            foreach($widget['validation'] as $name => $valid) {
                
                $this->form_validation->set_rules('widget['.$name.']',   $widget['parametrs'][$name][0],   $valid);
            }
            
            //Правила для валидации параметров кэша
            if ( $this->input->post('cache_enable') ) {
                
                $this->form_validation->set_rules('cache[usergroup]',    'lang:widget_cache_usergroup',   'trim|xss_clean');
                $this->form_validation->set_rules('cache[userid]',       'lang:widget_cache_userid',      'trim|xss_clean');
                $this->form_validation->set_rules('cache[segment]',      'lang:widget_cache_segment',     'trim|numeric|xss_clean');
                $this->form_validation->set_rules('cache[reload]',       'lang:widget_cache_reload',      'trim|numeric|xss_clean');
            }
            
            //Валидация
            if ( $this->form_validation->run() ) {
                
                $data['notification'] = lang('widget_add_success');
                $cache = null;
                
                if ( $this->input->post('cache_enable') ) {
                    
                    $cache = set_value('cache[]');
                }
                
                $this->adminmodel->add_widget( 
                      set_value('container'), set_value('title'), set_value('modul'), 
                      set_value('method'), set_value('widget[]'), set_value('order'), $cache);
                      
                $this->adminmodel->event_reset_cache();
            }
            else {
                
                $data['notification'] = $this->form_validation->error_string();
            }
        }
        
        //Загружаем контейнеры
        $data['containers'] = $this->adminmodel->get_widget_containers();
        
        //Загрузка модулей и виджетов
        $is_first = false;
        foreach($this->modmanager->get_modules() as $mod) {
            
            if (isset($mod->widgets) && count($mod->widgets) > 0) {
                
                $data['modules'][$mod->code] = $mod->title;
                
                if (!$is_first) {
                    
                    foreach ($mod->widgets as $name => $row) {
                        
                        $data['methods'][$name] = $row['title'];
                    }
                    $is_first = true;
                }
            }
        }
        
        parent::render($data, 'widget/add');
    }
    
    
    public function edit($id) {
        
        $this->load->helper('form');
        
        //Загружаем данные виджета
        $data['widget'] = $this->adminmodel->get_widget($id)->row_array();
        
        if ( $this->input->post('edit', TRUE) ) {
            
            $this->load->library('form_validation');
            
            $this->form_validation->set_rules('container',  'lang:widget_field_container',   'trim|required|xss_clean');
            $this->form_validation->set_rules('title',      'lang:widget_field_title',       'trim|xss_clean');
            $this->form_validation->set_rules('order',      'lang:widget_field_order',       'trim|required|is_natural|xss_clean');
            $this->form_validation->set_rules('widget[]',   'lang:widget_field_parametrs',   '');
            $this->form_validation->set_rules('cache[]',    'lang:widget_field_parametrs',   '');
            
            //Правила для валидации параметров виджета
            $modul = $this->modmanager->get_modul($data['widget']['modul']);
            $widget = $modul->widgets[$data['widget']['method']];
            
            foreach($widget['validation'] as $name => $valid) {
                
                $this->form_validation->set_rules('widget['.$name.']',   $widget['parametrs'][$name][0],   $valid);
            }
            
            //Правила для валидации параметров кэша
            if ( $this->input->post('cache_enable') ) {
                
                $this->form_validation->set_rules('cache[usergroup]',    'lang:widget_cache_usergroup',   'trim|xss_clean');
                $this->form_validation->set_rules('cache[userid]',       'lang:widget_cache_userid',      'trim|xss_clean');
                $this->form_validation->set_rules('cache[segment]',      'lang:widget_cache_segment',     'trim|numeric|xss_clean');
                $this->form_validation->set_rules('cache[reload]',       'lang:widget_cache_reload',      'trim|numeric|xss_clean');
            }
            
            //Валидация
            if ( $this->form_validation->run() ) {
                
                $data['notification'] = lang('success');
                $cache = null;
                
                if ( $this->input->post('cache_enable') ) {
                    
                    $cache = set_value('cache[]');
                }
                
                $this->adminmodel->edite_widget($id, set_value('container'), set_value('title'), set_value('widget[]'), set_value('order'), $cache);
                $this->adminmodel->event_reset_cache();
            }
            else {
                
                $data['notification'] = $this->form_validation->error_string();
            }
        }
        
        //Загружаем контейнеры
        $data['containers'] = $this->adminmodel->get_widget_containers();
        
        //Загружаем параметры кэша
        $data['cache'] = $this->widget->parse_cache_parametrs($data['widget']['cache']);
        $data['cache']['enable'] = ($data['widget']['cache'] == null) ? false : true;
        
        parent::render($data, 'widget/edite');
    }
    
    
    public function del($id) {
        
        $this->adminmodel->del_widget($id);
        $this->adminmodel->event_reset_cache();
        
        modul_redirect('widgets');
    }
    
    
    public function visible($id) {
        
        $this->load->helper('form');
        
        if ( $this->input->post('edit', TRUE) ) {
            
            $this->load->library('form_validation');
            
            $this->form_validation->set_rules('pages[]', 'lang:widget_field_pages', 'xss_clean');
            
            if ( $this->form_validation->run() ) {
                
                $data['notification'] = lang('success');
                
                $this->adminmodel->edite_widget_visible($id, set_value('pages[]'));
                $this->adminmodel->event_reset_cache();
            }
            else {
                
                $data['notification'] = $this->form_validation->error_string();
            }
        }
        
        $data['page'] = $this->load->tree();
        $data['widget'] = $this->adminmodel->get_widget($id)->row_array();
        $data['pages'] = ($data['widget']['pages'] == NULL) ? array() : unserialize($data['widget']['pages']);
        
        parent::render($data, 'widget/visible');
    }
    
    
    public function params($modul = false, $method = false, $params = '') {

        $this->load->helper('form');
        
        $modul  = ($modul === false) ? $this->input->post('modul') : $modul;
        $method = ($method === false) ? $this->input->post('method') : $method;
        
        if (!$modul || !$method) {
            
            
        }
        
        $mod = $this->modmanager->get_modul($modul);
        
        if (!property_exists($mod, 'widgets') && count($mod->widgets) <= 0) {
            
            
        }
        
        $data['fields'] = $this->adminmodel->get_widget_form_params($method, $mod, $params);
        parent::render($data, 'widget/params');
    }
    
    
    public function load($modul = false) {
        
        $modul = ($this->input->post('modul') !== false) ? $this->input->post('modul') : $modul;
        $mod = $this->modmanager->get_modul($modul);
        
        foreach ($mod->widgets as $name => $row) {
            
            $data[$name] = $row['title'];
        }
        
        parent::render(array('array' => $data, 'name' => 'method', 'id' => 'widget_method'), 'ajax_select');
    }
}